package io.finer.erp.jeecg.bas.service.impl;

import java.math.BigDecimal;
import java.text.ParseException;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.util.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import io.finer.erp.jeecg.bas.entity.BasCustomer;
import io.finer.erp.jeecg.bas.entity.DictItem;
import io.finer.erp.jeecg.bas.entity.ZrkOrderSalary;
import io.finer.erp.jeecg.bas.entity.ZrkShoporder;
import io.finer.erp.jeecg.bas.entity.ZrkUserCustomer;
import io.finer.erp.jeecg.bas.mapper.ZrkOrderSalaryMapper;
import io.finer.erp.jeecg.bas.service.IBasCustomerService;
import io.finer.erp.jeecg.bas.service.IZrkOrderSalaryService;
import io.finer.erp.jeecg.bas.service.IZrkShoporderService;
import io.finer.erp.jeecg.bas.service.IZrkUserCustomerService;
import io.finer.erp.jeecg.finance.entity.FinReceipt;
import io.finer.erp.jeecg.finance.entity.FinReceiptEntry;
import io.finer.erp.jeecg.finance.service.IFinReceiptEntryService;
import io.finer.erp.jeecg.finance.service.IFinReceiptService;

/**
 * @Description: 业务员回款统计表
 * @Author: jeecg-boot
 * @Date:   2020-09-18
 * @Version: V1.0
 */
@Service
public class ZrkOrderSalaryServiceImpl extends ServiceImpl<ZrkOrderSalaryMapper, ZrkOrderSalary> implements IZrkOrderSalaryService {
	@Autowired
	private IFinReceiptService receiptService;
	@Autowired
	private IFinReceiptEntryService receiptEntryService;
	@Autowired
	private IBasCustomerService customerService;
	@Autowired
	private IZrkUserCustomerService userCustomerService;
	@Autowired
	private IZrkShoporderService orderService;

	@Override
	public Result<?> addOrderSalaryAfterReceipt(String receiptId) {
		// TODO Auto-generated method stub
		FinReceipt receipt = receiptService.getById(receiptId);
		if(null == receipt) {
			return Result.error("未找到付款单");
		}
		List<FinReceiptEntry> receiptEntrys = receiptEntryService.selectByMainId(receiptId);
		if(receiptEntrys == null || receiptEntrys.size() == 0) {
			return Result.error("未找到付款单明细");
		}
		String customId = receipt.getCustomerId();
		if(StringUtils.isBlank(customId)) {
			return Result.error("未找到付款客户");
		}
		BasCustomer customer = this.customerService.getById(customId);
		if(customer == null) {
			return Result.error("未找到付款客户");
		}
		ZrkUserCustomer uc = userCustomerService.getByCustomerId(customId);
		String userId = uc.getUserId();
		if(null == uc || StringUtils.isBlank(userId)) {
			return Result.error("未找到客户对应的业务员");
		}
		Date customerDate = customer.getCreateTime();
		Date nowDate = DateUtils.getDate();
		Integer isOld = 0;
		if(Float.parseFloat(DateUtils.yearCompare(customerDate, nowDate)) >= 1) {
			isOld = 1;
		}
		for (FinReceiptEntry entry : receiptEntrys) {
//			String orderNo = entry.getSourceEntryNo();
//			if(StringUtils.isBlank(orderNo)) {
//				continue;
//			}
//			ZrkShoporder order = orderService.selectByOrderCode(orderNo);
//			
			String orderId = entry.getOrderId();
			ZrkShoporder order = orderService.getById(orderId);
			if(order == null) {
				continue;
			}
			ZrkOrderSalary salary = getByOrderId(orderId);
			BigDecimal entryMoney = entry.getAmt();
			if(null == salary) {
				salary = new ZrkOrderSalary();
				salary.setIsNewOrOld(isOld);
				salary.setUserId(userId);
				salary.setCreateTime(nowDate);
				salary.setCusId(customId);
				salary.setOrderId(orderId);
				salary.setOrderTime(order.getCreateTime());
				BigDecimal totalMoney = order.getOrderMoney();
				Calendar calendar = Calendar.getInstance();
				calendar.setTime(customerDate);
				Integer day = calendar.get(Calendar.DAY_OF_MONTH);
				Calendar calendarNow = Calendar.getInstance();
				calendarNow.setTime(order.getCreateTime());
				Integer year = calendarNow.get(Calendar.YEAR);
				Integer month = calendarNow.get(Calendar.MONTH);
				try {
					Date beginDate = DateUtils.date_sdf.get().parse(year.toString() + "-" + month.toString() + "-" + day.toString());
					salary.setStartTime(beginDate);
					Integer zhangqi = customer.getZhangqi();
					DictItem item = baseMapper.getDictItem("payment_days", zhangqi.toString());
					if(null != item) {
						String days = item.getItemText();
						String endDateStr = DateUtils.addDayNums(Integer.parseInt(days), beginDate);
						salary.setEndTime(DateUtils.date_sdf.get().parse(endDateStr));
					}
				} catch (ParseException e) {
					e.printStackTrace();
				}
//				addDayNums
				salary.setSalesMoney(totalMoney);
				if(entryMoney.compareTo(totalMoney) >= 0) {
					salary.setIsAllMoney(1);
					salary.setIsAll(1);
					salary.setBackTime(nowDate);
				}
				BigDecimal thirtyMoney = entryMoney.multiply(new BigDecimal("0.3"));
				thirtyMoney = thirtyMoney.setScale(2, BigDecimal.ROUND_DOWN);
				BigDecimal sevenMoney = entryMoney.multiply(new BigDecimal("0.7"));
				sevenMoney = sevenMoney.setScale(2, BigDecimal.ROUND_DOWN);
				salary.setThirtyMoney(thirtyMoney);
				salary.setSenventyMoney(sevenMoney);
				//判断客户是现金户还是账期户
				String backType = customer.getCashType();//1现金 2账期
				if("1".equals(backType)) {
					salary.setCashBackMoney(entryMoney);
				} else if ("2".equals(backType)) {
					salary.setPeriodBackMoney(entryMoney);
				}
				//TODO
				salary.setStartTime(order.getCreateTime());
				salary.setEndTime(order.getCreateTime());
				this.save(salary);
			} else {
				//判断客户是现金户还是账期户
				String backType = customer.getCashType();//1现金 2账期
				BigDecimal salaryMoney = BigDecimal.ZERO;
				if("1".equals(backType)) {
					BigDecimal cashMoney = salary.getCashBackMoney();
					if(null != cashMoney) {
						salaryMoney = salaryMoney.add(cashMoney);
					}
				} else if ("2".equals(backType)) {
					BigDecimal backMoney = salary.getPeriodBackMoney();
					if(null != backMoney) {
						salaryMoney = salaryMoney.add(backMoney);
					}
				}
				entryMoney = entryMoney.add(salaryMoney);
				BigDecimal thirtyMoney = entryMoney.multiply(new BigDecimal(0.3));
				thirtyMoney = thirtyMoney.setScale(2, BigDecimal.ROUND_DOWN);
				BigDecimal sevenMoney = entryMoney.multiply(new BigDecimal(0.7));
				sevenMoney = sevenMoney.setScale(2, BigDecimal.ROUND_DOWN);
				salary.setThirtyMoney(thirtyMoney);
				salary.setSenventyMoney(sevenMoney);
				if(entryMoney.compareTo(salary.getSalesMoney()) >= 0) {
					salary.setIsAllMoney(1);
					salary.setIsAll(1);
					salary.setBackTime(nowDate);
				}
				if("1".equals(backType)) {
					salary.setCashBackMoney(entryMoney);
				} else if ("2".equals(backType)) {
					salary.setPeriodBackMoney(entryMoney);
				}
				updateById(salary);
			}
		}
		return Result.ok();
	}

	private ZrkOrderSalary getByOrderId(String orderId) {
		LambdaQueryWrapper<ZrkOrderSalary> wrapper = new LambdaQueryWrapper<>();
		wrapper.eq(ZrkOrderSalary::getOrderId, orderId);
		List<ZrkOrderSalary> list = list(wrapper);
		if(list != null && list.size() != 0) {
			return list.get(0);
		}
		return null;
	}

}
